import xlrd
import xml.etree.ElementTree as ET
from xml.dom.minidom import parse
import xml.dom.minidom
EXCEL_PATH = "D:\\app\\res\\output.xls"
TARGET_RES = "D:\\app\\res\\"


def readExcel():
    excel = xlrd.open_workbook(EXCEL_PATH)
    table = excel.sheets()[0]  # 取第一个 sheet
    # excel工作表的行列操作
    n_rows = table.nrows  # 获取该sheet中的有效行数
    n_cols = table.ncols  # 获取该sheet中的有效列数
    print("excel row:" + str(n_rows) + ",col:" + str(n_cols))
    lan_list = table.row(rowx=0)  # 返回某行中所有的单元格对象组成的列表
    key_list = table.col(colx=0)  # 返回某列中所有的单元格对象组成的列表

    ##lan_list[0].value #获取某个cell 值
    for i in range(1, len(lan_list)):
        lan = lan_list[i].value
        lanDict = {}
        for k in range(1, len(key_list)):
            key = key_list[k].value
            value = table.cell(k, i).value
            lanDict[key] = value
        writeXml(getDirByLanguage(lan), lanDict)


# 写入XML要求
# 参考文档 https://cloud.tencent.com/developer/article/2066016
# 1、相同的key直接替换value
# 2、新增的key则插入到xml
def writeXml(dirName, lanDict):
    print("============>写入xml ：" + dirName + "...")
    print(lanDict)
    fileName = TARGET_RES+dirName+"\\strings.xml"
    DOMTree = xml.dom.minidom.parse(fileName)
    resource = DOMTree.documentElement
    stringNodes = resource.getElementsByTagName("string")
    for key in lanDict:
        stringNode = findNodeByName(stringNodes,key)
        if(stringNode == None):
            print("xml中未找到key为:%s 的节点，插入该key value" %key)
            newNode = DOMTree.createElement('string')
            newNode.setAttribute("name", key)
            textNode = DOMTree.createTextNode(lanDict[key])
            newNode.appendChild(textNode)
            resource.appendChild(newNode)
        else:
            # print("xml中找到key为:" + key)
            emptyContent =  len(stringNode.childNodes) == 0
            if(emptyContent):
                print("xml中找到key为:" + key + "的节点，更新该 value 为:" + lanDict[key])
                textNode = DOMTree.createTextNode(lanDict[key])
                stringNode.appendChild(textNode)
            elif(stringNode.firstChild.data != lanDict[key]):
                print("xml中找到key为:" + key + "的节点，更新该 value 为:" + lanDict[key])
                stringNode.firstChild.data = lanDict[key]

    # for strItem in stringNodes:
    #     nodeKey = strItem.getAttribute("name")
    #     nodeValue = strItem.childNodes[0].data
    with open(fileName, 'w', encoding='UTF-8') as writer:
        DOMTree.writexml(writer, indent='', addindent='  ', newl='\n', encoding='UTF-8')
        print("<============保存成功\n")

def findNodeByName(nodes,name):
    for strItem in nodes:
        nodeKey = strItem.getAttribute("name")
        if(name == nodeKey):
            return strItem

# 根据多语言 key 返回strings.xml对应文件夹路径
def getDirByLanguage(lan):
    return lan

readExcel()
